import { Module } from 'vuex'

import { ILoginState } from './type'
import { IRootState } from '../type'

import {
  accountLoginRequest,
  requestUserInfoById,
  requestUserMenusByRoleId
 } from '@/service/login/login'
import localCache from '@/utils/cache'
import { mapMenusToRoutes , mapMenusToPermissions} from '@/utils/map-menus'
import router from '@/router'

const loginModule: Module<ILoginState,IRootState> = {
  namespaced: true,
 state() {
   return {
     token: '',
     userInfo: {},
     userMenus:[],
     permissions:[]
   }
 },
 mutations:{
   changeToken(state,token: string) {
     state.token = token
   },
   changeUserInfo(state, userInfo: any){
     state.userInfo = userInfo
   },
   changeUserMenus(state, userMenus: any){
     state.userMenus = userMenus

     //userMenus => routes
     const routes = mapMenusToRoutes(userMenus)
    //  console.log(routes)

     //将routes => router.main.children
     //动态添加路由
    routes.forEach((route) => {
      router.addRoute('main',route)
    })

    //获取用户按钮权限
    const permissions = mapMenusToPermissions(userMenus)
    // console.log(permission,14578)
    state.permissions = permissions
   }
 },
 getters:{},
 actions:{
   async accountLoginAction({commit,dispatch}, payload: any){
     console.log('执行vuex中的登录方法',payload)
    //实现登录逻辑
    const loginResult = await accountLoginRequest(payload)
    const {id, token} = loginResult.data
    commit('changeToken', token)
    localCache.setCache('token', token)

    //发送初始化的请求(完整的role/department)
    dispatch('getInitialDataAction',null,{root:true})

    //请求用户信息
    const userInfoResult = await requestUserInfoById(id)
    const userInfo = userInfoResult.data
    commit('changeUserInfo', userInfo)
    localCache.setCache('userInfo', userInfo)
    //请求用户菜单
    const userMenusResult = await requestUserMenusByRoleId(userInfo.role.id)
    const userMenus = userMenusResult.data
    commit('changeUserMenus', userMenus)
    localCache.setCache('userMenus',userMenus)
    //跳转到首页
    router.push('/main')
   },
   phoneLoginAction({commit}, payload: any){
    console.log('执行vuex中的登录方法',payload)
  },
  loadLocalLogin({commit,dispatch}): any{
    const token = localCache.getCache('token')
    if(token){
      commit('changeToken',token)
      //发送初始化的请求(完整的role/department)
      dispatch('getInitialDataAction',null,{root:true})
    }
    const userInfo = localCache.getCache('userInfo')
    if(userInfo){
      commit('changeUserInfo',userInfo)
    }
    const userMenus = localCache.getCache('userMenus')
    if(userMenus){
      commit('changeUserMenus',userMenus)
    }
  }
 }
}

export default loginModule
